package com.jd.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jd.basic.exception.BusinessException;
import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.LoginData;
import com.jd.basic.jwt.RsaUtils;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.AjaxsResult;
import com.jd.basic.util.HttpUtil;
import com.jd.basic.util.Md5Utils;
import com.jd.basic.util.StrUtils;
import com.jd.system.domain.Menu;
import com.jd.system.mapper.MenuMapper;
import com.jd.system.mapper.PermissionMapper;
import com.jd.user.constant.WxConstants;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.domain.Wxuser;
import com.jd.user.dto.LoginDto;
import com.jd.user.mapper.LogininfoMapper;
import com.jd.user.mapper.UserMapper;
import com.jd.user.mapper.WxuserMapper;
import com.jd.user.service.ILogininfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //1.查询数据库中的account和type数据，用logininfo对象接收
        Logininfo logininfo = logininfoMapper.accountLogin(loginDto);
        //2.判断对象是否为null
        if (logininfo==null){
            throw new BusinessException("用户名错误");
        }else {
            // 将前端传来的密码加密加盐,再进行比较
            String inputPwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
            if (!inputPwd.equals(logininfo.getPassword())){
                //3.密码失败
                throw new BusinessException("密码错误");
            }else {
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                //密码正确，成功生成token,保存到redis中，设置过期时间30分钟
                /*String token = UUID.randomUUID().toString(); // 调用uuid方法生成token登录令牌
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

                //4.将token和对象参数存在map，返回前端
                Map<String, Object> map = new HashMap<>();// 创建一个map集合存放参数
                map.put("token",token); // 用于做登录拦截验证
                // 清空密码和盐值防止显示
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                // 回显前端用户信息
                map.put("logininfo",logininfo);*/
                return map;
            }
        }
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        Map<String, Object> map = new HashMap<>();
        map.put("logininfo",logininfo);
        //封装成一个LoginData对象
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);

        if(logininfo.getType()==0){//管理员
            //1.如果是后台管理员 - 获取当前登录人【logininfo.getId()】所有菜单
            List<Menu> menus = menuMapper.getMenuByLogininfoId(logininfo.getId()); //查询当前登录人的所有二级菜单以及所属的一级菜单
            //2.如果是后台管理员 - 获取当前登录人【logininfo.getId()】所有权限
            List<String> permissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
            loginData.setPermissions(permissions);
            loginData.setMenus(menus);
            map.put("menus",menus);
            map.put("permissions",permissions);
        }

        try {
            //3.获取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //4.通过私钥对LoginData对象进行加密，加密成jwt字符串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300);

            //5.将以上四个信息：logininfo，所有菜单，所有权限，jwtToken都要封装到Map进行返回 - 最终返回给前端
            //a.logininfo 返回给前端 - 回显信息
            //b.jwtToken 返回给前端 - 登陆权限
            //c.所有菜单  返回给前端 - 动态路由 - 实现动态菜单
            //d.所有权限  返回给前端 - 资源权限
            //疑问：jwtToken有这三个信息，但是需要解密 - but我们的前端没有解码。所以才要将logininfo，所有菜单，所有权限传递给前端
            map.put("token",jwtToken);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @Override
    public AjaxsResult wechatLogin(String code) {
        // 1.将请求参数替换
        String url = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        //2.使用httpuntil发送请求
        String jsonStr = HttpUtil.httpGet(url);
        //{"access_token":"57_3R0PHzOIKX6brh1TbBZKqwsOCHugjzrJeDZgssoAmsF_UFOq-TSTXE3tmZBUr7VIZ_eP71LhIzOeLeh4gua3vVligjDuBCjRiImEAPSAwqc","openid":"oa9wA01X4TNik8bbXWklIyArUZ5c",}
        //3.将响应的json字符串 转成 json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //4.通过openid查找wx对象
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);
        // 判断查询的id对象是否为空
        if (wxuser!= null && wxuser.getUserId()!=null){
            // 通过userid对象查询user对象
            User user = userMapper.loadById(wxuser.getUserId());
            if (user!=null){
                // 不为空，通过user对象中的logininfoid查找logininfo对象
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                // 设置过期时间
               /* String token = UUID.randomUUID().toString();
                redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
                // 将token和登录存在map中，返回
                Map<String, Object> map = new HashMap<>();
                map.put("token",token);
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                map.put("logininfo",logininfo);*/
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                return AjaxsResult.me().setResultObj(map);
            }
        }
        // 5.没有绑定，前端页面跳转到绑定页面
        String params = "?accessToken="+accessToken+"&openId="+openid;
        return AjaxsResult.me().setSuccess(false).setResultObj(params);

    }

    @Override
    public AjaxsResult wechatBinder(Map<String, String> map) {
        //1.获取用户前端传来的参数
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //2.校验电话和验证码
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为null");
        }
        // 验证码是否过期
        Object codeObj = redisTemplate.opsForValue().get("binder:"+phone);
        if (codeObj==null){
            throw new BusinessException("手机验证码过期");
        }
        if(!codeObj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("手机验证码错误");
        }
        //3.获取微信用户的信息，替换自己设置的数据
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);
        //4.处理获取的用户信息，将json字符串转化成wxuser对象
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //5.绑定
        //5.1先通过phone查找user是否有
        User user = userMapper.loadByPhone(phone);
        //5.2没有，就创建一个user对象，先添加到logininfo自增，user对象才有logininfo-id添加
        if (user==null){
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);//自增id
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);//自增id
        }
        //5.3有电话phone，保存到wxuser数据库
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        //6.免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        /*String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
        // 将token和登录信息存在map中
        Map<String,Object> result = new HashMap<>();
        result.put("token",token);
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        result.put("logininfo",logininfo);*/
        Map<String, Object> result = loginSuccessJwtHandler(logininfo);
        return AjaxsResult.me().setResultObj(result);

    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(4);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        String address = jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city");
        wxuser.setAddress(address);
        return wxuser;

    }
}


